package com.app.micaihu.receiver;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.app.micaihu.app.AppApplication;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.db.UserDBDAO;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.IPushManager;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ViewUtils;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.BindAliasCmdMessage;
import com.igexin.sdk.message.FeedbackCmdMessage;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.igexin.sdk.message.SetTagCmdMessage;
import com.igexin.sdk.message.UnBindAliasCmdMessage;


/**
 * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class DemoIntentService extends GTIntentService {

    private static final String TAG = "GetuiSdkDemo";

    public DemoIntentService() {

    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        LogUtils.e(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
        LogUtils.e(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));
        LogUtils.e(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg + "\ncid = " + cid);
        if (payload == null) {
            LogUtils.e(TAG, "receiver payload = null");
        } else {
            String data = new String(payload);
            LogUtils.e(TAG, "receiver payload = " + data);
            if (!StringUtils.isEmpty(data)) {
                open(context, data);
            }
        }
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        LogUtils.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
        AppConfigManager.getInstance().writeConfig(UserConfigTools.GT_CID, clientid);
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
//        LogUtils.e(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        LogUtils.e(TAG, "onReceiveCommandResult -> " + cmdMessage);

        int action = cmdMessage.getAction();

        if (action == PushConsts.SET_TAG_RESULT) {
            setTagResult((SetTagCmdMessage) cmdMessage);
        } else if (action == PushConsts.BIND_ALIAS_RESULT) {
            bindAliasResult((BindAliasCmdMessage) cmdMessage);
        } else if (action == PushConsts.UNBIND_ALIAS_RESULT) {
            unbindAliasResult((UnBindAliasCmdMessage) cmdMessage);
        } else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
            feedbackResult((FeedbackCmdMessage) cmdMessage);
        }
    }

    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage message) {
//        LogUtils.e(TAG, "onNotificationMessageArrived -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
//                + message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
//                + message.getTitle() + "\ncontent = " + message.getContent());
    }

    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage message) {
//        LogUtils.e(TAG, "onNotificationMessageClicked -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
//                + message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
//                + message.getTitle() + "\ncontent = " + message.getContent());
//
    }


    private void open(Context context, final String data) {
        NewsEntity newsEntity = null;
        try {
            newsEntity = GsonUtils.fromJson(data, NewsEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final NewsEntity finalNewsEntity = newsEntity;
        ViewUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (finalNewsEntity != null) {
                    String showType = finalNewsEntity.getShowType();
                    if (TextUtils.equals(showType, TypeConstant.PUSH_FOCUSNEWS)) {
                        //当前app运行并且在聚焦页面
//                        if (!IPushManager.getInstance().isAppIsInBackground(context)) {
//                            Activity lastActivity = AppManager.getAppManager().getLastActivity();
//                            if (lastActivity instanceof MainActivity) {
//                                boolean currentFragment = ((MainActivity) lastActivity).getCurrentFragment();
//                                LogUtils.e("gzq","c="+currentFragment);
////                                IPushManager.getInstance().showFoucsDialog(lastActivity, finalNewsEntity, TypeConstant.PUSHTYPE_UMENG);
//                            }
//                        } else {//记录到本地
                        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.push_foucusnews, data + "}_" + System.currentTimeMillis() + "}_" + TypeConstant.PUSHTYPE_UMENG);
                        AppConfigTools.isShowPushDialog = true;
//                        }
                    } else if (TextUtils.equals(showType, TypeConstant.PUSH_NORMAL)) {//不是要闻
                        String articleId = finalNewsEntity.getArticleId();
                        if (!TextUtils.isEmpty(articleId) && UserDBDAO.ReceiverHistoryDB(articleId)) {
                            return;
                        }
                        IPushManager.getInstance().showNotification(AppApplication.getInstance(), finalNewsEntity, TypeConstant.PUSHTYPE_UMENG);
                    }
                }
            }
        });
    }

    public static final String PRIMARY_CHANNEL = "default";

//    /**
//     * 显示通知栏(推送)
//     */
//    private void showNotification(Context context, PushBean pushBean, int articleId, String title, String summary) {
//        NotificationCompat.Builder builder;
//        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//        //判断是否是8.0Android.O
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel chan1 = new NotificationChannel(PRIMARY_CHANNEL, "Primary Channel", NotificationManager.IMPORTANCE_DEFAULT);
//            chan1.setLightColor(Color.GREEN);
//            chan1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
//            notificationManager.createNotificationChannel(chan1);
//            builder = new NotificationCompat.Builder(context, PRIMARY_CHANNEL);
//        } else {
//            builder = new NotificationCompat.Builder(context);
//        }
//        builder.setContentTitle(title);
//        builder.setContentText(summary);
//        builder.setSmallIcon(R.drawable.icon);
//        builder.setDefaults(Notification.DEFAULT_ALL);
//        builder.setAutoCancel(true);
//        Intent intent1 = null;
//        if (NewsListAdapter.IS_PAY.equals(pushBean.getNewsAttribute())) {
//            intent1 = new Intent(context, PayDetailsActivity.class);
//            intent1.putExtra(BaseActivity.PARAMETER2, "1018");
//        } else if (NewsListAdapter.IS_EARN.equals(pushBean.getNewsAttribute())) {
//            intent1 = new Intent(context, EarnListActivity.class);
//        } else if (NewsListAdapter.IS_AD.equals(pushBean.getNewsAttribute())) {
//            intent1 = new Intent(context, PayDetailsActivity.class);
//        } else if (NewsListAdapter.IS_JIANDAN.equals(pushBean.getNewsAttribute())) {
//            intent1 = new Intent(context, JianDanDetailActivity.class);
//            intent1.putExtra(BaseActivity.PARAMETER1, "pushDetail");
//            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent1.putExtra(BaseActivity.PARAMETER2, "1018");
//        } else {
//            intent1 = new Intent(context, DetailsActivity.class);
//            intent1.putExtra(BaseActivity.PARAMETER1, "pushDetail");
//            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent1.putExtra(BaseActivity.PARAMETER2, "1018");
//        }
//        intent1.putExtra("news", pushBean);
//        PendingIntent pendingIntent = PendingIntent.getActivity(context, articleId, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
//        builder.setContentIntent(pendingIntent);
//        Notification notification = builder.build();
//        try {
//            notificationManager.notify(articleId, notification);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    /**
//     * 推送消息(消息中心)
//     */
//    private void pushMessage(final PushForMsgCenter pushForMsgCenter, final Context context) {
//        String doMain = pushForMsgCenter.biz_info.service_domain;
//        if (BaseMsgSummaryBizInfoData.SERVICE_DO_MAIN_SYS.equals(doMain)) {
//            MsgCacheHelper.getInstence().getSysMsgById(Integer.parseInt(pushForMsgCenter.biz_info.last_msg_id), new MsgCacheHelper.OnFindSQLiteData<SysMsgData>() {
//                @Override
//                public void onSuccess(List<SysMsgData> list) {
//                    if (list == null) {
//                        showMsg(pushForMsgCenter, context);
//                    }
//                }
//            });
//
//        } else if (BaseMsgSummaryBizInfoData.SERVICE_DO_MAIN_COM.equals(doMain)) {
//            MsgCacheHelper.getInstence().getCommentMsgById(pushForMsgCenter.biz_info.last_msg_id, new MsgCacheHelper.OnFindSQLiteData<CommentMineData>() {
//                @Override
//                public void onSuccess(List<CommentMineData> list) {
//                    if (list == null) {
//                        showMsg(pushForMsgCenter, context);
//                    }
//                }
//            });
//        } else if (BaseMsgSummaryBizInfoData.SERVICE_DO_MAIN_PRA.equals(doMain)) {
//            MsgCacheHelper.getInstence().getPraiseMsgById(pushForMsgCenter.biz_info.last_msg_id, new MsgCacheHelper.OnFindSQLiteData<PraiseData>() {
//                @Override
//                public void onSuccess(List<PraiseData> list) {
//                    if (list == null) {
//                        showMsg(pushForMsgCenter, context);
//                    }
//                }
//            });
//        } else if (BaseMsgSummaryBizInfoData.SERVICE_DO_MAIN_FOLLOW.equals(doMain)) {
//
//            AppDBUtils<FollowMineData> appDBUtils = new AppDBUtils<FollowMineData>(FollowMineData.class);
//            appDBUtils.findDataById(pushForMsgCenter.biz_info.last_msg_id, new AppDBUtils.FindDBDataListener<FollowMineData>() {
//                @Override
//                public void onSuccess(List<FollowMineData> list) {
//                    if (list != null && list.size() != 0 && list.get(0) != null) {
//                        showMsg(pushForMsgCenter, context);
//                    }
//                }
//            });
//
//        } else {
//            showMsg(pushForMsgCenter, context);
//        }
//    }





    private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
        String sn = setTagCmdMsg.getSn();
        String code = setTagCmdMsg.getCode();

//        int text = R.string.add_tag_unknown_exception;
//        switch (Integer.valueOf(code)) {
//            case PushConsts.SETTAG_SUCCESS:
//                text = R.string.add_tag_success;
//                break;
//
//            case PushConsts.SETTAG_ERROR_COUNT:
//                text = R.string.add_tag_error_count;
//                break;
//
//            case PushConsts.SETTAG_ERROR_FREQUENCY:
//                text = R.string.add_tag_error_frequency;
//                break;
//
//            case PushConsts.SETTAG_ERROR_REPEAT:
//                text = R.string.add_tag_error_repeat;
//                break;
//
//            case PushConsts.SETTAG_ERROR_UNBIND:
//                text = R.string.add_tag_error_unbind;
//                break;
//
//            case PushConsts.SETTAG_ERROR_EXCEPTION:
//                text = R.string.add_tag_unknown_exception;
//                break;
//
//            case PushConsts.SETTAG_ERROR_NULL:
//                text = R.string.add_tag_error_null;
//                break;
//
//            case PushConsts.SETTAG_NOTONLINE:
//                text = R.string.add_tag_error_not_online;
//                break;
//
//            case PushConsts.SETTAG_IN_BLACKLIST:
//                text = R.string.add_tag_error_black_list;
//                break;
//
//            case PushConsts.SETTAG_NUM_EXCEED:
//                text = R.string.add_tag_error_exceed;
//                break;
//
//            default:
//                break;
//        }
//
//        Log.d(TAG, "settag result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
    }

    private void bindAliasResult(BindAliasCmdMessage bindAliasCmdMessage) {
        String sn = bindAliasCmdMessage.getSn();
        String code = bindAliasCmdMessage.getCode();

//        int text = R.string.bind_alias_unknown_exception;
//        switch (Integer.valueOf(code)) {
//            case PushConsts.BIND_ALIAS_SUCCESS:
//                text = R.string.bind_alias_success;
//                break;
//            case PushConsts.ALIAS_ERROR_FREQUENCY:
//                text = R.string.bind_alias_error_frequency;
//                break;
//            case PushConsts.ALIAS_OPERATE_PARAM_ERROR:
//                text = R.string.bind_alias_error_param_error;
//                break;
//            case PushConsts.ALIAS_REQUEST_FILTER:
//                text = R.string.bind_alias_error_request_filter;
//                break;
//            case PushConsts.ALIAS_OPERATE_ALIAS_FAILED:
//                text = R.string.bind_alias_unknown_exception;
//                break;
//            case PushConsts.ALIAS_CID_LOST:
//                text = R.string.bind_alias_error_cid_lost;
//                break;
//            case PushConsts.ALIAS_CONNECT_LOST:
//                text = R.string.bind_alias_error_connect_lost;
//                break;
//            case PushConsts.ALIAS_INVALID:
//                text = R.string.bind_alias_error_alias_invalid;
//                break;
//            case PushConsts.ALIAS_SN_INVALID:
//                text = R.string.bind_alias_error_sn_invalid;
//                break;
//            default:
//                break;
//
//        }

//        Log.d(TAG, "bindAlias result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));

    }

    private void unbindAliasResult(UnBindAliasCmdMessage unBindAliasCmdMessage) {
        String sn = unBindAliasCmdMessage.getSn();
        String code = unBindAliasCmdMessage.getCode();

//        int text = R.string.unbind_alias_unknown_exception;
//        switch (Integer.valueOf(code)) {
//            case PushConsts.UNBIND_ALIAS_SUCCESS:
//                text = R.string.unbind_alias_success;
//                break;
//            case PushConsts.ALIAS_ERROR_FREQUENCY:
//                text = R.string.unbind_alias_error_frequency;
//                break;
//            case PushConsts.ALIAS_OPERATE_PARAM_ERROR:
//                text = R.string.unbind_alias_error_param_error;
//                break;
//            case PushConsts.ALIAS_REQUEST_FILTER:
//                text = R.string.unbind_alias_error_request_filter;
//                break;
//            case PushConsts.ALIAS_OPERATE_ALIAS_FAILED:
//                text = R.string.unbind_alias_unknown_exception;
//                break;
//            case PushConsts.ALIAS_CID_LOST:
//                text = R.string.unbind_alias_error_cid_lost;
//                break;
//            case PushConsts.ALIAS_CONNECT_LOST:
//                text = R.string.unbind_alias_error_connect_lost;
//                break;
//            case PushConsts.ALIAS_INVALID:
//                text = R.string.unbind_alias_error_alias_invalid;
//                break;
//            case PushConsts.ALIAS_SN_INVALID:
//                text = R.string.unbind_alias_error_sn_invalid;
//                break;
//            default:
//                break;
//
//        }
//
//        Log.d(TAG, "unbindAlias result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));

    }


    private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
        String appid = feedbackCmdMsg.getAppid();
        String taskid = feedbackCmdMsg.getTaskId();
        String actionid = feedbackCmdMsg.getActionId();
        String result = feedbackCmdMsg.getResult();
        long timestamp = feedbackCmdMsg.getTimeStamp();
        String cid = feedbackCmdMsg.getClientId();
        LogUtils.e(TAG, "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nactionid = " + actionid + "\nresult = " + result
                + "\ncid = " + cid + "\ntimestamp = " + timestamp);
    }
}
